package com.yunc.common.schedule;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunc.modules.sys.entity.SysJob;
import com.yunc.modules.sys.entity.SysJobLog;
import com.yunc.modules.sys.service.ISysJobLogService;
import com.yunc.modules.sys.service.ISysJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * 扩展job
 *
 * @author congcong tao
 * @date 2018/11/10 10:27
 */
public abstract class AbstractScheduleJob implements Job {

    @Autowired
    private ISysJobService sysJobService;
    @Autowired
    private ISysJobLogService sysJobLogService;

    private static final Logger logger = LoggerFactory.getLogger(AbstractScheduleJob.class);

    public abstract void before(JobExecutionContext context);

    public abstract void doWork(JobExecutionContext context);

    public abstract void after(JobExecutionContext context);

    @Override
    public void execute(JobExecutionContext context) {
        // 开始时间
        String startTime = DateUtil.formatDateTime(new Date());
        JobKey jobKey = context.getTrigger().getJobKey();
        SysJob jobRecord = new SysJob();
        jobRecord.setJobName(jobKey.getName());
        jobRecord.setJobGroup(jobKey.getGroup());
        SysJob sysJob = sysJobService.getOne(new QueryWrapper<>(jobRecord));
        String name = context.getTrigger().getJobKey().getName();
        SysJobLog jobLog = new SysJobLog();
        jobLog.setJobName(sysJob.getJobName());
        jobLog.setJobGroup(sysJob.getJobGroup());
        jobLog.setMethodName(sysJob.getMethodName());
        jobLog.setCreateTime(new Date());
        before(context);
        long startTimeL = System.currentTimeMillis();
        try {
            // 执行成功
            doWork(context);
            long times = System.currentTimeMillis() - startTimeL;
            // 任务状态 0：成功 1：失败
            jobLog.setIsException("0");
            jobLog.setJobMessage(sysJob.getJobName() + " 总共耗时：" + times + "毫秒");

        } catch (Exception e) {
            long times = System.currentTimeMillis() - startTimeL;
            logger.info("未查询到任务,任务名:{}，时间:{}", name, new Date());
            jobLog.setJobMessage(sysJob.getJobName() + " 总共耗时：" + times + "毫秒");
            // 任务状态 0：成功 1：失败
            jobLog.setIsException("1");
            jobLog.setExceptionInfo(e.toString());
        } finally {
            sysJobLogService.save(jobLog);
        }
        after(context);
    }
}
